<?php

declare(strict_types=1);

namespace app\middleware;

use app\common\system\logic\FormLogic;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Token
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {

        $token = $request->header("X-Token");
        if (empty($token)) return \error([], '参数无效', 300);

        try {
            $ini = config();
            $key = $ini['app']['jwt'];
            $data = JWT::decode($token, new Key($key, 'HS256'));
        } catch (\UnexpectedValueException $e) {
            return \error([], $e->getMessage(), 300);
        }

        // token验证
        $user = (array)$data;
        if (empty($user)) return \error([], 'token无效', 300);

        $post = $request->post();

        // 验证表单token
        if (isset($post['form_token']) && !empty($post['form_token'])) {
            $formLogic = new FormLogic();
            $checkRs = $formLogic->checkToken($post['form_token'], $user['id']);
            if (!$checkRs) {
                return error([], '表单已提交或已超时，请重新刷新', 400);
            }
        }

        $request->user = $user;
        // 接口权限验证
        return $next($request);
    }
}
